package com.dhcc.bpm.modules.gateway.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.dhcc.bpm.common.annotation.Log;
import com.dhcc.bpm.common.enums.BusinessType;
import com.dhcc.bpm.common.enums.ConfigType;
import com.dhcc.bpm.common.json.JSONObject;
import com.dhcc.bpm.common.redisMessage.RedisMessageSender;
import com.dhcc.bpm.modules.api.entity.Product;
import com.dhcc.bpm.modules.gateway.entity.Authcenter;
import com.dhcc.bpm.modules.gateway.entity.Gateway;
import com.dhcc.bpm.modules.gateway.service.IAuthcenterService;
import com.dhcc.bpm.modules.gateway.service.IGatewayRouteService;
import com.dhcc.bpm.modules.gateway.service.IGatewayService;
import com.dhcc.bpm.modules.gateway.vo.GatewayRouteVO;
import com.dhcc.bpm.modules.gateway.vo.GatewayVO;
import com.dhcc.bpm.modules.system.service.ISerialNumberService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.google.common.base.Joiner;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;
/**
 * @ClassName GatewayController
 * @Description 网关表 控制器
 * @Author YaoZC
 * @Date 2019/11/26 16:08
 * @Version 1.0
 * @Copyright: 2019 东华软件 . All rights reserved.
 */
@RestController
@AllArgsConstructor
@RequestMapping("bpm-gateway/gateway")
@Api(value = "网关表", tags = "网关表接口")
class GatewayController extends BladeController {
	private static final Logger log = LoggerFactory.getLogger(GatewayController.class);

	private IGatewayService gatewayService;
	@Autowired
	private RedisMessageSender redisMessageSender;

	private ISerialNumberService serialNumberService;

	private IAuthcenterService authcenterService;
	@Autowired
	private IGatewayRouteService gatewayRouteService;
	/**
	 * @Description 查看网关详情
	 * @Date 2019/11/27 15:02
	 * @param gateway
	 * @return org.springblade.core.tool.api.R<com.dhcc.bpm.modules.gateway.entity.Gateway>
	 **/
	@ApiLog("查看网关详情")
	@GetMapping("/detail")
	@ApiOperationSupport(order = 1)
	@ApiOperation(value = "详情", notes = "传入gateway")
	@Log(title = "查看网关详情",businessType = BusinessType.SELECT)
	public R<Gateway> detail(Gateway gateway) {
		Gateway detail = gatewayService.getOne(Condition.getQueryWrapper(gateway));
		return R.data(detail);
	}

	/**
	 * @Description 查看网关分页列表
	 * @Date 2019/11/27 15:02
	 * @param gateway
	 * @param query
	 * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage<com.dhcc.bpm.modules.gateway.entity.Gateway>>
	 **/
	@ApiLog("查看网关分页列表")
	@GetMapping("/list")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入gateway")
	@Log(title = "查看网关分页列表",businessType = BusinessType.SELECT)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "gatewayName", value = "网关名称", paramType = "query", dataType = "string"),
			@ApiImplicitParam(name = "gatewayCode", value = "网关编码", paramType = "query", dataType = "string"),
			@ApiImplicitParam(name = "messageType", value = "报文类型", paramType = "query", dataType = "string"),
			@ApiImplicitParam(name = "accessProtocol", value = "访问协议", paramType = "query", dataType = "string"),
			@ApiImplicitParam(name = "breakCycle", value = "熔断周期", paramType = "query", dataType = "string"),
			@ApiImplicitParam(name = "createUser", value = "创建者", paramType = "query", dataType = "string"),
			@ApiImplicitParam(name = "env", value = "环境", paramType = "query", dataType = "string"),
	})
	public R<IPage<Gateway>> list(@ApiIgnore @RequestParam Map<String, Object> gateway, Query query) {
		IPage<Gateway> pages = gatewayService.page(Condition.getPage(query), Condition.getQueryWrapper(gateway, Gateway.class));
		return R.data(pages);
	}

	/**
	 * @Description 查看网关分页列表
	 * @Date 2019/11/27 15:02
	 * @param gateway
	 * @param query
	 * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage<com.dhcc.bpm.modules.gateway.entity.Gateway>>
	 **/
	@ApiLog("查看网关分页列表")
	@GetMapping("/fetchGatewayList")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页", notes = "传入gateway")
	@Log(title = "查看网关分页列表",businessType = BusinessType.SELECT)
	public R<IPage<GatewayVO>> fetchGatewayList(GatewayVO gateway, Query query) {
		List<String> list = authcenterService.findAllIds(gateway.getId());
//		List<String> ids = new ArrayList<>();
//		list.forEach(listStr ->{
//			String[] str = listStr.split(",");
//			for(int i = 0; i< str.length; i++){
//				ids.add(str[i]);
//			}
//		});
		gateway.setGateway(Joiner.on(",").join(list));
		IPage<GatewayVO> pages = gatewayService.selectGatewayList(Condition.getPage(query), gateway);
		return R.data(pages);
	}

	/**
	 * @Description 查看网关自定义分页列表
	 * @Date 2019/11/27 15:02
	 * @param gateway
	 * @param query
	 * @return org.springblade.core.tool.api.R<com.baomidou.mybatisplus.core.metadata.IPage<com.dhcc.bpm.modules.gateway.vo.GatewayVO>>
	 **/
	@ApiLog("查看网关分页列表")
	@GetMapping("/page")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "分页", notes = "传入gateway")
	@Log(title = "查看网关自定义分页列表",businessType = BusinessType.SELECT)
	public R<IPage<GatewayVO>> page(GatewayVO gateway, Query query) {
		IPage<GatewayVO> pages = gatewayService.selectGatewayPage(Condition.getPage(query), gateway);
		return R.data(pages);
	}

	/**
	 * @Description 网关新增
	 * @Date 2019/11/27 15:02
	 * @param gateway
	 * @return org.springblade.core.tool.api.R
	 **/
	@ApiLog("网关新增")
	@PostMapping("/save")
	@ApiOperationSupport(order = 4)
	@ApiOperation(value = "新增", notes = "传入gateway")
	@Log(title = "网关新增", businessType = BusinessType.INSERT)
	public R save(@Valid @RequestBody Gateway gateway) {
		gateway.setRefreshPath("0");
		gateway.setRefreshStatus("0");
		return R.status(gatewayService.save(gateway));
	}

	/**
	 * @Description 网关修改
	 * @Date 2019/11/27 15:02
	 * @param gateway
	 * @return org.springblade.core.tool.api.R
	 **/
	@ApiLog("网关修改")
	@PostMapping("/update")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "修改", notes = "传入gateway")
	@Log(title = "网关修改", businessType = BusinessType.UPDATE)
	public R update(@Valid @RequestBody Gateway gateway) {
		gateway.setRefreshStatus("0");
		return R.status(gatewayService.updateById(gateway));
	}

	/**
	 * @Description 网关新增或修改
	 * @Date 2019/11/27 15:02
	 * @param gateway
	 * @return org.springblade.core.tool.api.R
	 **/
	@ApiLog("网关新增修改")
	@PostMapping("/submit")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "网关新增或修改", notes = "传入gateway")
	@Log(title = "网关新增或修改", businessType = BusinessType.INSERT)
	public R submit(@Valid @RequestBody Gateway gateway) {
		if(gateway.getId() == null){
			String date = serialNumberService.generateSerialNumberByModelCode("opc_gateway_date");
			String code = serialNumberService.generateSerialNumberByModelCode("opc_gateway_num");
			String dateStr = date.substring(0,date.length()-1);
			gateway.setGatewayCode(dateStr + code);
			gateway.setRefreshPath("0");
			gateway.setPrivilegeLevel("0");
		}
		gateway.setRefreshStatus("0");
		gatewayService.saveOrUpdate(gateway);
		return R.data(gateway);
	}

	
	/**
	 * @Description 网关删除
	 * @Date 2019/11/27 15:01
	 * @param ids
	 * @return org.springblade.core.tool.api.R
	 **/
	@ApiLog("网关删除")
	@PostMapping("/remove")
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	@Log(title = "网关删除", businessType = BusinessType.DELETE)
	public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
		List<Long> idList = Func.toLongList(ids);
		for(int i = 0; i< idList.size(); i++){
			List<GatewayRouteVO> list = gatewayRouteService.getByGatewayId(idList.get(i));
			if(list.size() > 0){
				return R.fail(222, "该网关存在路由暂时无法删除！");
			}
		}
		return R.status(gatewayService.deleteLogic(Func.toLongList(ids)));
	}

	/**
	 * @Description 刷新网关路由
	 * @Date 2019/11/27 15:02
	 * @param env
	 * @return org.springblade.core.tool.api.R<com.dhcc.bpm.modules.gateway.entity.GatewayRoute>
	 **/
	@ApiLog("刷新网关路由")
	@PostMapping("/refreshRoute")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "刷新网关路由", notes = "传入网关编码gatewayCode")
	@Log(title = "刷新网关路由", businessType = BusinessType.REFRESH)
	public R refreshRoute(@ApiParam(value = "主键集合", required = true) @RequestParam String env,
			@ApiParam(value = "网关编码", required = true) @RequestParam String gatewayCode) {
		try {
			String message = redisMessageSender.format(ConfigType.ROUTE.name(), "刷新路由配置信息");
			redisMessageSender.sendMessageToGateway(gatewayCode, message);
			String messageInt = redisMessageSender.format(ConfigType.API.name(), "刷新接口配置");
			redisMessageSender.sendMessageToGateway(gatewayCode, messageInt);
			String msg = redisMessageSender.format(ConfigType.RATELIMET.name(), "刷新限流配置");
			redisMessageSender.sendMessageToGateway(gatewayCode, msg);
			//管理端不使用redis推送刷新token  修改时间：20200927 21:03:00
//			String token = redisMessageSender.format(ConfigType.TOKEN.name(), "刷新Token信息");
//			redisMessageSender.sendMessageToGateway("", token);
			String route = redisMessageSender.format(ConfigType.ALARM.name(), "刷新告警配置");
			redisMessageSender.sendMessageToGateway(gatewayCode, route);
			String apiWhiteBlack = redisMessageSender.format(ConfigType.APIWHITEBLACK.name(), "刷新API黑白名单");
			redisMessageSender.sendMessageToGateway(gatewayCode, apiWhiteBlack);
			String gatewayWhiteBlack = redisMessageSender.format(ConfigType.GATEWAYWHITEBLACK.name(), "刷新网关黑白名单");
			redisMessageSender.sendMessageToGateway(gatewayCode, gatewayWhiteBlack);
			String appSecret = redisMessageSender.format(ConfigType.APPSECRET.name(), "刷新产品公私钥配置");
			redisMessageSender.sendMessageToGateway(gatewayCode, appSecret);
			String params = redisMessageSender.format(ConfigType.PARAMS.name(), "刷新参数配置");
			redisMessageSender.sendMessageToGateway(gatewayCode, params);
			String remain = redisMessageSender.format(ConfigType.REMAIN.name(), "刷新剩余配置");
			redisMessageSender.sendMessageToGateway(gatewayCode, remain);
			Gateway gateway = new Gateway();
			gateway.setRefreshStatus("1");
			gateway.setEnv(env);
			int result = gatewayService.updateRefreshStatus(gateway);
			if(result>=0){
				return R.status(true);
			}
			return R.status(false);
		}catch (Exception e){
			log.error("刷新网关路由失败:{}", e);
			return R.status(false);
		}
	}
	/**
	 * @Description 根据网关ID查询产品列表
	 * @Date 2020/3/6 10:19
	 * @param gatewayId
	 * @return org.springblade.core.tool.api.R
	 **/
	@ApiLog("根据网关ID查询产品列表")
	@GetMapping("/productByGatewayId")
	@ApiOperationSupport(order = 9)
	@ApiOperation(value = "根据网关ID查询产品列表", notes = "传入gatewayId")
	@Log(title = "根据网关ID查询产品列表",businessType = BusinessType.SELECT)
	public R productListByGatewayId(String gatewayId, Product product, Query query) {
		IPage<Product> pages = gatewayService.productListByGatewayId(Condition.getPage(query), product,gatewayId);
		return R.data(pages);
	}
	/**
	 * @Description 查询网关名称
	 * @Date 2020/3/6 10:19
	 * @return org.springblade.core.tool.api.R
	 **/
	@ApiLog("查询网关名称")
	@GetMapping("/selectGatewayName")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "查询网关名称", notes = "")
	@Log(title = "查询网关名称",businessType = BusinessType.SELECT)
	public JSONObject selectGatewayName() {
		JSONObject object = new JSONObject();
		object.put("success", true);
		object.put("names", gatewayService.selectGatewayName());
		return object;
	}

	/**
	 * @Description 查询网关名称
	 * @Date 2020/3/6 10:19
	 * @return org.springblade.core.tool.api.R
	 **/
	@ApiLog("查询网关名称")
	@GetMapping("/selectGatewayNameById")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "查询网关名称", notes = "")
	@Log(title = "查询网关名称",businessType = BusinessType.SELECT)
	public JSONObject selectGatewayNameById(Long id) {
		JSONObject object = new JSONObject();
		object.put("success", true);
		Authcenter auth = authcenterService.getById(id);
		object.put("names", gatewayService.selectGatewayNameById(auth.getGateway()));
		return object;
	}

}
